<?php
/**
 * Created by PhpStorm.
 * User: zyark
 * Date: 2017/8/29
 * Time: 15:26
 */

namespace Home\Logic;


use Admin\Logic\MoneyLogLogic;
use Common\Utils\Constants;
use Think\Exception;
use Think\Log;
use Home\Model\Page;

class UserLogic
{
    /**
     * 绑定上级
     * @param $openid string openid
     * @param $recommend_id int 推荐人id
     * @return int 0失败 1成功
     */
    public function bindUser($openid,$recommend_id){
        $user = D('User')->where(array('openid'=>':openid'))->bind(array(':openid'=>$openid))->find();
        if($user){
            return $user;
        }
        //推荐人
        $recommendUser = D('User')->where(array('id'=>$recommend_id))->find();

        $model = M();
        $model->startTrans();
        try {
            $user['openid'] = $openid.'';
            $user['user_type'] = Constants::USER_TYPE_ORDINARY;
            $user['recommend_id'] = $recommend_id.'';
            $user['create_time'] = time();
            Log::write('recommend_id---:'.$recommend_id);
            $user_id = $model->table('t_user')->add($user);
            Log::write('sql:'.$model->getLastSql());
            //直推人数加1
            $model->table('t_user')->where(array('id' => $recommend_id))->setInc('recommend', 1);
            if (!empty($recommendUser['last_one'])) {//存在代理用户 last_one为所属代理id
                $model->table('t_user')->where(array('id' => $user_id))->setField('last_one', $recommendUser['last_one']);
            }
            if($recommendUser['user_type'] == Constants::USER_TYPE_AGENT){
                $model->table('t_user')->where(array('id' => $user_id))->setField('last_one', $recommend_id);
            }
            $model->commit();
            return 1;
        }catch (Exception $e){
            Log::write($e->getMessage());
            $model->rollback();
            return 0;
        }
    }

    /**
     *创建用户并绑定上级
     * @param $openId string  微信openid
     * @param $super_id int 上级id
     * @return array $user 用户信息
     */
    public function bindSuperior($openId,$super_id){
//        $model = D('User');
//
//
//
//        $this->bindUser($user_id,$super_id);
//        return $user;
    }

    //普通用户推广奖励金币
    public function rewardGold($recommend_id,$user_id,$model){
        $config = $model->table('t_config')->where(array('name'=>Constants::CONFIG_PROMOTION_GOLD))->find();
//                    $room = $model->table('t_room')->where(array('id'=>$log['room_id']))->find();
        $money = $config['value'];
        if(is_numeric($money) && $money > 0) {//奖励金币
            $recommendUser = $model->table('t_user')->where(array('id' => $recommend_id))->find();

            $model->table('t_user')->where(array('id' => $recommend_id))->setInc('gold', $money);
            $moneyLogic = new MoneyLogLogic();
            $nickname = D('User')->where(array('id'=>$user_id))->getField('nickname');
            $remark = '邀请'.$nickname.'加入获得金币';
            $moneyLogic->saveMoneyLogBySourceId($config['value'],
                $recommendUser['gold'] + $money,
                Constants::MONEY_SOURCE_PROMOTION,
                Constants::PUT_TYPE_IN,
                $remark,$recommendUser['id'],Constants::MONEY_TYPE_GOLD,$user_id,$model);
        }
    }

    /**
     * 分页条件查询
     * @param $map 查询条件
     * @param $pagenumber 页号
     * @param $pagesize 页面大小
     * @return mixed
     */
    public function getByConditionPage($map, $pagenumber, $pagesize)
    {
        $startno = ($pagenumber - 1) * $pagesize;
        $limit = $startno . ',' . $pagesize;//每页的数据数和内容$limit
        $list = D('User')->where($map)->limit($limit)->order('id desc')
            ->select();
        $logic = new MatchLogLogic();
        foreach ($list as $key=>$value){
            $list[$key]['create_time'] = date('Y/m/d',$value['create_time']);
            if(!empty($value['register_time'])) {
                $list[$key]['register_time'] = date('Y/m/d', $value['register_time']);
            }else{
                $list[$key]['register_time'] = '';
            }
            $list[$key]['battle_times'] = $logic->getBattleTimes($value['id']);
        }
        $data['list'] = $list;
        $count = D('User')->where($map)->count();
        $page = new Page($pagenumber, $count, $pagesize);
        $page = (array)$page;//转换为数组
        $data['page'] = $page;
        return $data;
    }



    /**
     * 用户首次进入存到数据库
     * @param $openid
     * @param $nickname
     * @param $sex
     * @param $head_url
     * @return int user_id
     */
    public function addUser($openid,$nickname,$sex,$head_url){
        $user['openid'] = $openid.'';
        $user['nickname'] = $nickname;
        $user['sex'] = $sex;
        $user['head_url'] = $head_url;
        $user['create_time'] = time();
        $user_id = D('User')->add($user);
        return $user_id;
    }

    /**
     * 修改用户信息
     * @param $data array 用户信息
     * @return int
     */
    public function modifyUserInfo($data){
        $model = M();
        $model->startTrans();
        try{
            $user = $model->table('t_user')->where(array('id'=>$data['id']))->find();
            if(empty($user['phone'])){
                $first = true;//首次完善资料
                $user['register_time'] = time();
            }else{
                $first = false;
            }
            $user['phone'] = $data['phone'];
            $user['wechat_number'] = $data['wechat_number'];
            $user['game_name'] = $data['game_name'];
            $user['systems_name'] = $data['systems_name'];
            $user['region'] = $data['region'];
            $user['region_name'] = $data['region_name'];
            $user['qq_number'] = $data['qq_number'];
            $user['level'] = $data['level'];
            $model->table('t_user')->save($user);
            if(!empty($user['recommend_id']) && $first){//首次完善资料后 直推人获得奖励
                $recommendUserType = $model->table('t_user')->where(array('id'=>$user['recommend_id']))->getField('user_type');
                if($recommendUserType == Constants::USER_TYPE_ORDINARY){
                    $this->rewardGold($user['recommend_id'],$user['id'],$model);
                }

            }

            $model->commit();
            return 1;
        }catch (Exception $e){
            Log::write('modifyUserInfo---:'.$e->getMessage());
            $model->rollback();
            return 0;
        }
    }

    /**
     * 用户注册奖励钻石
     * @param $user_id int 用户id
     * @return int 0失败 1成功 2已经领取过
     */
    public function rewardIntegralByRegister($user_id){
        $user = D('User')->where(array('id'=>$user_id))->find();
        if($user['is_first'] == 1){
            $model = M();
            $model->startTrans();
            try{
                $this->rewardIntegral($user['id'],$model);
                $this->registerRewardGold($user['id'],$model);
                $model->table('t_user')->where(array('id'=>$user_id))->setField('is_first',0);//不是首次进入
                $this->addRankingDataByUser($user_id,$model);//初始化排行榜数据
                $model->commit();
                return 1;
            }catch (Exception $e){
                $model->rollback();
                Log::write("rewardIntegralByRegister:".$e->getMessage());
                return 0;
            }
        }
        return 2;
    }

    /**
     * 新用户注册奖励钻石
     * @param $user_id
     * @param $model
     */
    private function rewardIntegral($user_id,$model){
        $config = $model->table('t_config')->where(array('name'=>Constants::CONFIG_REGISTER_REWARD_INTEGRAL))->find();
        $money = $config['value'];
        if(is_numeric($money) && $money > 0) {//奖励钻石
            $model->table('t_user')->where(array('id' => $user_id))->setInc('integral', $money);
            $currentIntegral = $model->table('t_user')->where(array('id' => $user_id))->getField('integral');
            $moneyLogic = new MoneyLogLogic();
            $remark = '新用户注册奖励钻石';
            $moneyLogic->saveMoneyLog($money,
                $currentIntegral,
                Constants::MONEY_SOURCE_GIVE,
                Constants::PUT_TYPE_IN,
                $remark, $user_id, Constants::MONEY_TYPE_INTEGRAL, $model);
        }
    }

    /**
     * 用户注册奖励金币500
     * @param $user_id
     * @param $model
     */
    private function registerRewardGold($user_id,$model){
        $money = 500;
        $model->table('t_user')->where(array('id' => $user_id))->setInc('gold', $money);
        $currentGold = $model->table('t_user')->where(array('id' => $user_id))->getField('gold');
        $moneyLogic = new MoneyLogLogic();
        $remark = '新用户注册奖励金币';
        $moneyLogic->saveMoneyLog($money,
            $currentGold,
            Constants::MONEY_SOURCE_GIVE,
            Constants::PUT_TYPE_IN,
            $remark, $user_id, Constants::MONEY_TYPE_GOLD, $model);
    }

    /**
     * 初始化排行榜数据
     * @param $user_id int 用户id
     * @param $model
     */
    public function addRankingDataByUser($user_id,$model){
        $this->addRankingDataByType($user_id,Constants::MODEL_TYPE_1V1,$model);
        $this->addRankingDataByType($user_id,Constants::MODEL_TYPE_3V3,$model);
        $this->addRankingDataByType($user_id,Constants::MODEL_TYPE_5V5,$model);
    }

    private function addRankingDataByType($user_id,$type,$model){
        $data['user_id'] = $user_id;
        $data['type'] = $type;
        $model->table('t_ranking')->add($data);
    }

    /**
     * 增加用户推广页面访问量
     * @param $user_id int 用户id 二维码页面所属者
     * @param $visitors_id int 访问者id
     * @param $is_new_register bool 是否新注册
     */
    public function visitor($user_id,$visitors_id,$is_new_register){
        $model = M();
        $model->startTrans();
        try{
            if($user_id == $visitors_id){
                return;
            }
            $count = D('BrowseLog')->where(array('user_id'=>$user_id,'visitors_id'=>$visitors_id))->count();
            if($count > 0){
               return;
            }
            $log['user_id'] = $user_id;
            $log['visitors_id'] = $visitors_id;
            $log['create_time'] = time();
            $model->table('t_browse_log')->add($log);
            $this->countPageViews($user_id,$model);
            if($is_new_register){
                $this->bindUserByPush($visitors_id,$user_id,$model);
            }
            $model->commit();
        }catch (Exception $e){
            Log::write('visitor--:'.$e->getMessage());
            $model->rollback();
        }
    }

    /**
     * 统计用户浏览量
     * @param $user_id int 用户id
     * @param $model
     */
    private function countPageViews($user_id,$model){
        //增加用户浏览量
        $pageviews_proportion = $config = D('Config')->where(array('name'=>Constants::CONFIG_PAGEVIEWS_PROPORTION))->find();
        $pageviews_proportion = $pageviews_proportion['value'];
        $model->table('t_user')->where(array('id'=>$user_id))->setInc('pageviews',1);//真实浏览量加1
        $model->table('t_user')->where(array('id'=>$user_id))->setInc('count_pageviews',1);//累计浏览量加1
        if(is_numeric($pageviews_proportion) && $pageviews_proportion !=0){
            $user = $model->table('t_user')->where(array('id'=>$user_id))->field('count_pageviews,show_pageviews,pageviews')->find();
            $count_pageviews = floor($user['count_pageviews'] * $pageviews_proportion);
            if($count_pageviews >= 1){
                if($pageviews_proportion > 1){
                    $current = $user['count_pageviews'] - $count_pageviews;
                }else{
                    $current = $user['count_pageviews'] - floor($count_pageviews/$pageviews_proportion);
                }
                if($current < 1){
                    $current = 0;
                }
                $model->table('t_user')->where(array('id'=>$user_id))->setInc('show_pageviews',$count_pageviews);//显示浏览量加$count_pageviews
                $model->table('t_user')->where(array('id'=>$user_id))->setField('count_pageviews',$current);//修改累计
            }
        }
    }

    /**
     * 通过分享二维码绑定上级
     * @param $user_id
     * @param $recommend_id
     * @param $model
     */
    private function bindUserByPush($user_id,$recommend_id,$model){
        //推荐人
        $recommendUser = D('User')->where(array('id'=>$recommend_id))->find();
        $model->table('t_user')->where(array('id' => $recommend_id))->setInc('recommend', 1);
        $model->table('t_user')->where(array('id' => $user_id))->setField('recommend_id', $recommend_id);
        if (!empty($recommendUser['last_one'])) {//存在代理用户 last_one为所属代理id
            $model->table('t_user')->where(array('id' => $user_id))->setField('last_one', $recommendUser['last_one']);
        }
        if($recommendUser['user_type'] == Constants::USER_TYPE_AGENT){
            $model->table('t_user')->where(array('id' => $user_id))->setField('last_one', $recommend_id);
        }
    }

    /**
     * 申请代理
     * @param $user_id
     * @return array status 0
     */
    public function applyAgent($user_id){
        $model = M();
        $model->startTrans();
        try{
            $money = 30000;
            $count = $model->table('t_money_log')
                ->where(array('user_id'=>$user_id,'money_type'=>Constants::MONEY_TYPE_INTEGRAL,'type'=>Constants::MONEY_SOURCE_APPLY_AGENT))
                ->count();
            if($count !=0 ){
                return array('status'=>3);//已经申请过代理
            }
            $user = $model->table('t_user')->where(array('id'=>$user_id))->field('integral,user_type')->find();
            if($user['user_type'] == 1){
                return array('status'=>4); //已经是代理用户
            }
            $integral = $user['integral'];
            if($integral < $money){
                return array('status'=>2);
            }
            $model->table('t_user')->where(array('id'=>$user_id))->setDec('integral',$money);
            $moneyLogic = new MoneyLogLogic();
            $remark = '申请代理';
            $moneyLogic->saveMoneyLog($money,
                $integral - $money,
                Constants::MONEY_SOURCE_APPLY_AGENT,
                Constants::PUT_TYPE_OUT,
                $remark, $user_id, Constants::MONEY_TYPE_INTEGRAL, $model);
            $model->commit();
            return array('status'=>1);
        }catch (Exception $e){
            $model->rollback();
            Log::write('applyAgent:------'.$e->getMessage());
            return array('status'=>0,'error'=>$e->getMessage());
        }
    }

    /**
     * 用户用户前端显示的浏览量信息
     * @param $user_id int 用户id
     * @return array show_pageviews money
     */
    public function getUserPageViews($user_id){
        $show_pageviews = D('User')->where(array('id'=>$user_id))->getField('show_pageviews');
        $to_money = $config = D('Config')->where(array('name'=>Constants::CONFIG_PAGEVIEWS_TO_MONEY))->find();
        $to_money = $to_money['value'];
        $money =0;
        if(is_numeric($to_money) && $to_money !=0){
            $money = $to_money * $show_pageviews;
        }
        return array('show_pageviews'=>$show_pageviews,'money'=>$money);
    }

    /**
     * 创建或更新用户信息
     * @param $open_id
     * @param $user_info
     * @return $this|array|false|\PDOStatement|string|\think\Model
     */
    public function saveOrUpdateUser($open_id,$user_info){
        $open_id = $open_id.'';
        $user = M('User')
            ->where(array('openid'=>$open_id))
            ->find();
        if(!$user){
            //创建用户
            $user_info = $this->makeUser($user_info,$user);
            $user_info['openid'] = $open_id.'';
            $user_info['create_time'] = time();
            $user_id = M('User')->add($user_info);
            $user = M('User')->where(array('id'=>$user_id))->find();
        }else{
            $user_info = $this->makeUser($user_info,$user);
            M('User')->where(array("id"=>$user['id']))->save($user_info);
        }
        return $user;
    }

    private function makeUser($userInfo,$user){
        $user['nickname'] =  match_chinese($userInfo->nickname);
        $user['head_url'] = $userInfo->headimgurl;
        $sex = $userInfo->sex.'';
        $user['sex'] = $sex == '2' ? 1 : 0;
        return $user;
    }

    /**
     * 添加用户信息
     * @param $data array 用户信息
     * @return mixed
     */
    public function addUserInfo($data){
        $model = M();
        $model->startTrans();
        try{
            $first = true;//首次完善资料
            $user['create_time'] = time();
            $user['register_time'] = time();
            $user['phone'] = $data['phone'];
            $user['wechat_number'] = $data['wechat_number'];
            $user['game_name'] = $data['game_name'];
            $user['systems_name'] = $data['systems_name'];
            $user['region'] = $data['region'];
            $user['region_name'] = $data['region_name'];
            $user['qq_number'] = $data['qq_number'];
            $user['level'] = $data['level'];
            $user['head_url'] = $data['head_url'];
            $user['nickname'] = $data['nickname'];
            $user['password'] = md5($data['password'].''.$user['register_time']);
            if(isset($data['recommend_id'])){
                $user['recommend_id'] = $data['recommend_id'];
            }
            $user_id = $model->table('t_user')->add($user);
            if(isset($user['recommend_id']) && !empty($user['recommend_id']) && $first){//首次完善资料后 直推人获得奖励
                //直推人数加1
                $recommend_id = $user['recommend_id'];
                //推荐人
                $recommendUser = D('User')->where(array('id'=>$recommend_id))->find();
                $model->table('t_user')->where(array('id' => $recommend_id))->setInc('recommend', 1);
                if (!empty($recommendUser['last_one'])) {//存在代理用户 last_one为所属代理id
                    $model->table('t_user')->where(array('id' => $user_id))->setField('last_one', $recommendUser['last_one']);
                }
                if($recommendUser['user_type'] == Constants::USER_TYPE_AGENT){
                    $model->table('t_user')->where(array('id' => $user_id))->setField('last_one', $recommend_id);
                }
                $recommendUserType = $model->table('t_user')->where(array('id'=>$user['recommend_id']))->getField('user_type');
                if($recommendUserType == Constants::USER_TYPE_ORDINARY){
                    $this->rewardGold($user['recommend_id'],$user_id,$model);
                }
            }
            $model->commit();
            return 1;
        }catch (Exception $e){
            Log::write('modifyUserInfo---:'.$e->getMessage());
            $model->rollback();
            return 0;
        }
    }

}